package com.showcal.service.listener;

import com.alibaba.fastjson.JSON;
import com.showcal.service.biz.MessageManager;
import com.showcal.service.domain.MessageBusinessTypeEnum;
import com.showcal.service.event.IMMessageSendEvent;
import com.showcal.service.event.bean.IMMessagBean;
import com.showcal.service.po.QuestionPO;
import com.showcal.service.request.IMMessageAddRequest;
import com.showcal.service.request.SendIMMessageRequest;
import com.xiniunet.framework.security.Passport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 保存消息
 * Created by guzhixiong on 2015/11/17.
 */
@Component
public class SaveIMMessageListener implements ApplicationListener<IMMessageSendEvent> {
    @Autowired
    private MessageManager messageManager;
    @Async
    @Override
    public void onApplicationEvent(IMMessageSendEvent imMessageSendEvent) {
        System.out.println("do Save IM Message");
        IMMessagBean imMessagBean = (IMMessagBean) imMessageSendEvent.getSource();
        SendIMMessageRequest request = imMessagBean.getImMessageRequest();
        QuestionPO newQuestion = imMessagBean.getQuestion();
        Passport passport = imMessagBean.getPassport();
        IMMessageAddRequest messageCreateRequest = new IMMessageAddRequest();
        messageCreateRequest.setMessageId(request.getMessageId());
        messageCreateRequest.setType(MessageBusinessTypeEnum.QUESTION);
        messageCreateRequest.setServiceId(newQuestion.getId());
        messageCreateRequest.setMessageContent(JSON.toJSONString(request.getContent()));
        messageCreateRequest.setMessageType(request.getContent().getContentType());
        messageCreateRequest.setFromUserId(passport.getUserId()); //从我
        messageCreateRequest.setToUserId(request.getShowcalId()); //到showcal
        messageManager.addIMMessage(messageCreateRequest, passport);
    }
}
